<template>
  <div class="preview-container">
    <div class="title-box">
      <div class="title">{{ schemeName }}</div>
      <div class="stu-info">
        <span>姓名:</span>
        <span>{{ user.name }}</span>
        <span class="stu-info">科类:</span>
        <span v-if="infos.majorType == 1">理科</span>
        <span v-if="infos.majorType == 2">文科</span>
        <span v-if="infos.majorType == 3">艺术理</span>
        <span v-if="infos.majorType == 4">艺术文</span>
        <span v-if="infos.majorType == 5">体育理</span>
        <span class="stu-info">批次:</span>
        <span>{{ batch }}</span>
        <span class="stu-info">分数:</span>
        <span>{{ user.score }}</span>
        <span class="stu-info">位次:</span>
        <span>{{ user.precedence }}</span>
      </div>
    </div>

    <div class="table-section">
      <el-table :data="tableData" v-loading="loading" ref="elTable"
                element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading"
                style="width: 100%;" default-expand-all :cell-style="{background: '#fff2e7'}">
        <!-- 展开表格 S -->
        <el-table-column type="expand" width="30px">
          <template slot="header" slot-scope="scope">
            <div @click="toggleExpansionAll" class="el-table__expand-icon" :class="isExpansion && `el-table__expand-icon--expanded`">
              <i class="el-icon el-icon-arrow-right"></i>
            </div>
          </template>
          <template slot-scope="props">
            <el-table :data="props.row.majorList" style="width: 100%;" :header-cell-style="{display: 'none'}" >
              <el-table-column width="30px"><span></span></el-table-column>
              <ColProbability label="录取概率" />
              <el-table-column prop="sort" width="100">
                <template slot-scope="props">
                  <div style="display: flex;align-items: center">
                    <span style="font-weight:bolder">{{ props.row.sort }}</span>
                    <el-popover
                        v-if="props.row.examLimit"
                        placement="top-start"
                        width="200"
                        trigger="hover"
                        :content="props.row.examLimit">
                      <div slot="reference"><i class="el-icon-warning" style="font-size: 16px;color: #f00;padding: 6px 10px;"></i></div>
                    </el-popover>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="majorCode" width="70"></el-table-column>
              <el-table-column prop="majorName"></el-table-column>
              <el-table-column prop="plan2018" width="90" align="center"></el-table-column>
              <el-table-column prop="majorLimit" width="90" align="center"></el-table-column>
              <el-table-column width="70" align="center">
                <template slot-scope="scopes">
                  <div class="sort-box">
                    <div class="sort-item">
                      <i class="el-icon-top" @click="risemajor(scopes,props)"></i>
                    </div>
                    <div class="sort-item">
                      <i class="el-icon-bottom" @click="declinemajor(scopes,props)"></i>
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column width="89" align="center">
                <template slot-scope="scope">
                  <el-dropdown trigger="click" style="margin: 0;padding: 0 5px;">
                    <span class="el-dropdown-link" :class="props.row.sort?'scheme':'not-scheme'"
                          style="margin: 0;cursor: pointer;">
                      <el-button type="text" size="small" style="color: #67C23A">修改</el-button>
                    </span>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item v-for="(item,index) in majorNameList" :key="index" :command="item.label"
                                        style="padding: 0;text-align: center;">
                        <span
                            @click="updateMajor(props.$index, scope.$index, JSON.stringify(tableData[props.$index].majorList), item.label)"
                            style="width: 60px;padding: 10px;">{{ item.label }} </span>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                  <el-button type="text" size="small"
                             @click.native.prevent="deleteRow(scope.$index, tableData[props.$index].majorList)">删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <!-- 展开表格 E -->
        <ColProbability v-if="user.precedence" label="录取概率" />
        <el-table-column prop="programmeId" label="序列" width="100">
          <template slot-scope="scope">
            <div style="display: flex;align-items: center">
              <span style="font-weight:bolder">{{ scope.row.schemeName }}</span>
              <el-popover
                  v-if="scope.row.schoolExamLimit"
                  placement="top-start"
                  width="600"
                  trigger="hover"
                  :content="scope.row.schoolExamLimit">
                <div slot="reference"><i class="el-icon-warning" style="font-size: 16px;color: #f00;padding: 6px 10px;"></i></div>
              </el-popover>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="programmeName" label="代码" width="70">
          <template slot-scope="scope">
            <span style="font-weight:bolder">{{ scope.row.schoolCode }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="programmeName" align="center" label="院校名称(录取形式)/专业(类)|包含专业及其等级">
          <template slot-scope="scope">
            <div class="text-left">
              <span style="font-weight:bolder">{{ scope.row.schoolName }}</span>
              <span style="float: right;font-weight:bolder">
                <span style="margin-left: 30px;" v-show="Admission">{{ scope.row.majorPlan }}|</span>
                服从调剂：
                <el-radio v-model="scope.row.schemeChange" label="0" style="margin-right: 10px">是</el-radio>
                <el-radio v-model="scope.row.schemeChange" label="1">否</el-radio>
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="计划" width="90" align="center">
          <template slot-scope="scope">
            <span style="font-weight:bolder">{{ scope.row.plan2022 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="学费(元/年)" width="90" align="center">
        </el-table-column>
        <el-table-column label="调序" width="70" align="center">
          <template slot-scope="scope">
            <div class="sort-box">
              <div class="sort-item">
                <i class="el-icon-top" @click="risescheme(scope)"></i>
              </div>
              <div class="sort-item">
                <i class="el-icon-bottom" @click="decline(scope)"></i>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="programmeName" label="操作" width="90" align="center">
          <template slot-scope="scope">
            <el-dropdown trigger="click" style="margin: 0;padding: 0 5px;">
              <span class="el-dropdown-link" :class="scope.row.schemeName?'scheme':'not-scheme'"
                    style="margin: 0;cursor: pointer;font-size: 15px;">
                <el-button type="text" size="small" style="color: #67C23A">修改</el-button>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-for="(item,index) in schemeNameList" :key="index" :command="item.label"
                                  style="padding: 0;text-align: center;">
                  <span @click="updateScheme(scope.$index,item.label)" style="width: 60px;padding: 10px;">{{
                      item.label
                    }}</span>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <el-button type="text" size="small" @click="deleteScheme(scope.$index,tableData,scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="right-btn-box">
      <el-button style="background-color: #f96630;" circle @click="saveScheme()">保存</el-button>
      <el-button style="background-color: #67C23A;" circle @click="update()">修改</el-button>
      <el-button style="background-color: #7870b6;" circle @click="goToAdministration()">上一级</el-button>
      <!-- <el-button style="background-color: #7870b6;" circle @click="goSeniorSchool()">新高考</el-button> -->
    </div>

  </div>
</template>

<script>
import {request} from '@/util/request'
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'

export default {
  inject: ['reload'],
  data() {
    return {
      isExpansion: true,
      // 预览title
      schemeName: '',
      switchStyle: 'blue',
      place: null,
      Admission: false,
      fraction: '',
      batch: '',
      infos: [],
      tableData: [],
      loading: true,
      stuId: '',
      user: [],
      del: [],
      majorList: [],
      setIds: [],
      dropList: [
        {
          value: '1',
          label: '志愿A'
        },
        {
          value: '2',
          label: '志愿B'
        },
        {
          value: '3',
          label: '志愿C'
        },
        {
          value: '4',
          label: '志愿D'
        },
        {
          value: '5',
          label: '志愿E'
        },
        {
          value: '6',
          label: '志愿F'
        },
        {
          value: '7',
          label: '备选'
        },
        {
          value: '8',
          label: '取消'
        },
      ],
      zyList: [{
        value: '1',
        label: '专业1'
      },
        {
          value: '2',
          label: '专业2'
        },
        {
          value: '3',
          label: '专业3'
        },
        {
          value: '4',
          label: '专业4'
        },
        {
          value: '5',
          label: '专业5'
        },
        {
          value: '6',
          label: '专业6'
        },
        {
          value: '7',
          label: '备选'
        },
        {
          value: '8',
          label: '取消'
        },
      ],
      schemeNameList: [
        {
          value: '志愿A',
          label: '志愿A'
        },
        {
          value: '志愿B',
          label: '志愿B'
        },
        {
          value: '志愿C',
          label: '志愿C'
        },
        {
          value: '志愿D',
          label: '志愿D'
        },
        {
          value: '志愿E',
          label: '志愿E'
        },
        {
          value: '志愿F',
          label: '志愿F'
        },
        {
          value: '备选',
          label: '备选'
        }
      ],
      majorNameList: [{
        value: '专业1',
        label: '专业1'
      },
        {
          value: '专业2',
          label: '专业2'
        },
        {
          value: '专业3',
          label: '专业3'
        },
        {
          value: '专业4',
          label: '专业4'
        },
        {
          value: '专业5',
          label: '专业5'
        },
        {
          value: '专业6',
          label: '专业6'
        },
        {
          value: '备选',
          label: '备选'
        }
      ],
    }
  },
  mounted() {

  },
  methods: {
    toggleExpansionAll() {
      this.isExpansion = !this.isExpansion
      this.tableData.map(item => this.$refs.elTable.toggleRowExpansion(item, this.isExpansion))
    },
    getPdf(url) {
      var title = this.schemeName
      html2Canvas(document.querySelector(url), {
        allowTaint: true,
        taintTest: false,
        logging: false,
        useCORS: true,
        dpi: window.devicePixelRatio * 1.5, //将分辨率提高到特定的DPI 提高四倍
        // dpi:300,
        scale: 1.5 //按比例增加分辨率
      }).then(canvas => {
        var pdf = new JsPDF('p', 'mm', 'a4');    //A4纸，纵向

        var ctx = canvas.getContext('2d'),
            a4w = 240, a4h = 260,    //A4大小，210mm x 297mm，四边各保留10mm的边距，显示区域190x277
            imgHeight = Math.floor(a4h * canvas.width / a4w),    //按A4显示比例换算一页图像的像素高度
            renderedHeight = 0;
        ctx.mozImageSmoothingEnabled = false;
        ctx.webkitImageSmoothingEnabled = false;
        ctx.msImageSmoothingEnabled = false;
        ctx.imageSmoothingEnabled = false;
        while (renderedHeight < canvas.height) {
          var page = document.createElement("canvas");
          page.width = canvas.width;
          page.height = Math.min(imgHeight, canvas.height - renderedHeight);//可能内容不足一页

          //用getImageData剪裁指定区域，并画到前面创建的canvas对象中
          page.getContext('2d').putImageData(ctx.getImageData(0, renderedHeight, canvas.width, Math.min(imgHeight, canvas.height - renderedHeight)), 0, 0);
          pdf.addImage(page.toDataURL('image/jpeg', 1.0), 'JPEG', -15, 10, a4w, Math.min(a4h, a4w * page.height / page.width));    //添加图像到页面，保留10mm边距

          renderedHeight += imgHeight;
          if (renderedHeight < canvas.height) {
            pdf.addPage();//如果后面还有内容，添加一个空页
          }
        }
        //保存文件
        pdf.save(title + '.pdf')

      })
    },
    updateMajor(schoolIndex, majorIndex, majorList, name) {
      let majorArray = JSON.parse(majorList);
      majorArray.forEach(function (item, index) {
        if (majorIndex === index) {
          item.sort = name;
        }
      });
      this.tableData[schoolIndex].majorList = majorArray;
      this.saveScheme();
    },
    deleteRow(index, rows) {
      this.$confirm('确定删除专业嘛?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        rows.splice(index, 1);
        this.saveScheme();
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    zyb () {
      let sortList = []
      let bList = []
      for (var i = 0; i < this.tableData.length; i++) {
        if (this.tableData[i].schemeName == "备选") {
          bList.push(this.tableData[i])
        } else {
          sortList.push(this.tableData[i])
        }
      }
      bList.forEach(i => {
        sortList.push(i)
      })
      this.tableData = sortList
      for (let m = 0; m < this.tableData.length; m++) {
        let sortList = []
        let bList = []
        for (var i = 0; i < this.tableData[m].majorList.length; i++) {
          console.log(this.tableData[m].majorList[i]);
          if (this.tableData[m].majorList[i].sort == "备选") {
            bList.push(this.tableData[m].majorList[i])
          } else {
            sortList.push(this.tableData[m].majorList[i])
          }
        }
        bList.forEach(i => {
          sortList.push(i)
        })
        this.tableData[m].majorList = sortList
      }
    },
    saveScheme () {
      this.scheme = []
      this.tableData.forEach(i => {
        this.scheme.push({
          "id": i.id,
          "schoolCode": i.schoolCode,
          "schoolName": i.schoolName,
          "majorList": i.majorList ? JSON.stringify(i.majorList).toString() : null,
          "programmeName": i.programmeName,
          "schemeName": i.schemeName,
          "programmeId": i.programmeId,
          "stuId": i.stuId,
          "batch": i.batch,
          "fraction": i.fraction,
          "num": i.num,
          "schemeChange": i.schemeChange,
          "majorPlan": i.majorPlan,
          "plan2022": i.plan2022,
          "majorType": i.majorType,
        })
      })
      this.scheme.forEach(a => {
        this.setIds.forEach(v => {
          if (a.id === v.id) {
            a.schemeChange = v.schemeChange
          }
        })
      })
      request({
        method: 'post',
        url: 'stuScheme/saveScheme',
        data: this.scheme
      }).then(res => {
        if (res.code == 0 || res.code == 200) {
          this.$message.success({
            message: '保存成功！',
            duration: 1000
          });
          this.dialogVisible = false
        } else {
          this.$message.error({
            message: '保存失败！',
            duration: 1000
          });
        }
      })
    },
    risescheme(row) {
      if (row.$index > 0) {
        let changeDate = this.tableData[row.$index];
        let nextDate = this.tableData[row.$index - 1];
        this.tableData[row.$index] = nextDate;
        this.tableData[row.$index - 1] = changeDate;
        this.zyb()
      }
    },
    risemajor(row, l) {
      if (row.$index > 0) {
        let changeDate = this.tableData[l.$index].majorList[row.$index];
        let nextDate = this.tableData[l.$index].majorList[row.$index - 1];
        this.tableData[l.$index].majorList[row.$index] = nextDate;
        this.tableData[l.$index].majorList[row.$index - 1] = changeDate;
        this.zyb()
      }
    },
    decline(row) {
      if (row.$index < (this.tableData.length - 1)) {
        let changeDate = this.tableData[row.$index];
        let prevDate = this.tableData[row.$index + 1];
        this.tableData[row.$index] = prevDate;
        this.tableData[row.$index + 1] = changeDate;
        this.zyb()
      }
    },
    declinemajor(row, l) {
      if (row.$index < (this.tableData[l.$index].majorList.length - 1)) {
        let changeDate = this.tableData[l.$index].majorList[row.$index];
        let prevDate = this.tableData[l.$index].majorList[row.$index + 1];
        this.tableData[l.$index].majorList[row.$index] = prevDate;
        this.tableData[l.$index].majorList[row.$index + 1] = changeDate;
        this.zyb()
      }
    },
    goToAdministration() {
      this.$router.push({
        path: '/design/management'
      })
    },
    update() {
      const programme = this.tableData;
      const user = sessionStorage.getItem("user");
      let stu = JSON.parse(user)
      let majorType = this.infos.majorType;
      programme.forEach(function (item, index) {
        if (item.majorType === null) {
          item.majorType = majorType;
        }
      });
      this.$router.push({
        path: '/design/programme',
        query: {
          programme: JSON.stringify(programme)
        }
      })
      // if (stu.userType == 4) {
      //   this.$router.push({
      //     path: '/design/studentProgramme',
      //     query: {
      //       programme: JSON.stringify(programme)
      //     }
      //   })
      // } else {
      //   this.$router.push({
      //     path: '/design/programme',
      //     query: {
      //       programme: JSON.stringify(programme)
      //     }
      //   })
      // }
    },

    goSeniorSchool() {
      const programme = this.tableData;
      this.$router.push({
        path: '/designV2/seniorSchool',
        query: {
          examineeId: this.stuId,
          student: JSON.stringify(programme)
        }
      })
    },
    updateName() {
      request({
        method: 'POST',
        url: 'stuScheme/updateName',
        params: {
          name: this.schemeName,
          programmeId: this.tableData[0].programmeId,
          stuId: this.stuId
        }
      }).then(res => {
        if (res.code == 0 || res.code == 200) {
          this.$message({
            showClose: true,
            message: '修改成功',
            type: 'success'
          });
        }
      })
    },
    updateScheme(index, schemeName) {
      this.tableData[index].schemeName = schemeName;
      this.saveScheme();
    },
    deleteScheme(index, rows, row) {
      this.$confirm('确定删除该志愿嘛?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (rows.length <= 1) {
          this.$message({
            message: '至少保留一个志愿~',
            type: 'error'
          });
        } else {
          request({
            method: 'POST',
            url: 'stuScheme/deleteScheme',
            params: {
              Id: row.id,
            }
          }).then(res => {
            if (res.code == 0 || res.code == 200) {
              rows.splice(index, 1);
              this.$message({
                message: '删除成功！',
                type: 'success'
              });
            } else {
              this.$message({
                message: '删除失败~',
                type: 'error'
              });
            }
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    getScheme() {
      request({
        method: 'POST',
        url: 'stuScheme/getScheme',
        params: {
          stuId: this.stuId,
          programmeId: this.infos.programmeId,
          batch: this.infos.batch
        }
      }).then(res => {
        this.tableData = res.data
        this.fraction = this.tableData[0].fraction
        this.batch = this.tableData[0].batch
        this.place = this.tableData[0].ranking
        if (this.batch == '国家专项' || this.batch == '地方专项' || this.batch == '本科一批' || this.batch == '本科二批' || this.batch == '高职专科') {
          this.Admission = true
        }
        for (let i = 0; i < res.data.length; i++) {
          this.tableData[i].majorList = res.data[i].majorList ? JSON.parse(res.data[i].majorList) : []
        }
        if (this.batch == "本科二批") {
          this.schemeNameList = [
            {
              value: '志愿A',
              label: '志愿A'
            },
            {
              value: '志愿B',
              label: '志愿B'
            },
            {
              value: '志愿C',
              label: '志愿C'
            },
            {
              value: '志愿D',
              label: '志愿D'
            },
            {
              value: '志愿E',
              label: '志愿E'
            },
            {
              value: '志愿F',
              label: '志愿F'
            },
            {
              value: '志愿G',
              label: '志愿G'
            },
            {
              value: '志愿H',
              label: '志愿H'
            },
            {
              value: '志愿I',
              label: '志愿I'
            },
            {
              value: '志愿J',
              label: '志愿J'
            },
            {
              value: '志愿K',
              label: '志愿K'
            },
            {
              value: '志愿L',
              label: '志愿L'
            },
            {
              value: '备选',
              label: '备选'
            }]
        } else if (this.batch == "高职专科") {
          this.schemeNameList = [{
            value: '志愿A',
            label: '志愿A'
          },
            {
              value: '志愿B',
              label: '志愿B'
            },
            {
              value: '志愿C',
              label: '志愿C'
            },
            {
              value: '志愿D',
              label: '志愿D'
            },
            {
              value: '志愿E',
              label: '志愿E'
            },
            {
              value: '志愿F',
              label: '志愿F'
            },
            {
              value: '志愿G',
              label: '志愿G'
            },
            {
              value: '志愿H',
              label: '志愿H'
            },
            {
              value: '备选',
              label: '备选'
            }]
        }
        this.schemeName = this.tableData[0].programmeName
        this.loading = false
        this.zyb()
      })
    },
  },
  created() {
    this.infos = this.$route.params.info
    this.infos = JSON.parse(localStorage.getItem('volunteer'))
    const user = localStorage.getItem("stu");
    this.user = JSON.parse(user)
    this.stuId = this.user.id
    this.timer = setTimeout(() => {   //设置延迟执行
      this.getScheme()
    }, 1000);

  }
}
</script>

<style lang="stylus">
.preview-container
  .el-table th.el-table__cell
    background-color: #f0f0f0;

  .el-table__expanded-cell[class*=cell]
    padding: 0;

  .right-btn-box
    .el-button
      width: 60px;
      height: 60px;
      padding: 0;
      margin-bottom: 20px;
      text-align center
      color: #fff;
    .el-button+.el-button
      margin-left: 0;
</style>
<style lang="stylus" scoped>
pageWidth = 1400px
$color-theme = #f96630
.preview-container
  width: pageWidth;
  min-height: BodyMinHeight;
  margin: 0 auto;
  font-size: 16px;

  .title-box
    padding: 20px 0;
    line-height: 40px;
    text-align: center;

    .title
      font-size: 20px;
      font-weight: bold;

    span
      font-size: 16px;
      margin-left: 5px;

    .stu-info
      margin-left: 30px;


  .table-section
    padding: 0 5% 40px 5%;

    .sort-box
      display: flex;
      align-items: center;
      cursor: pointer;
      text-align: center;

      .sort-item
        flex: 1;
        text-align: center;
        line-height: 30px;
        color: $color-theme;

  .right-btn-box
    position: fixed;
    top: 50%;
    margin-top: -120px;
    right: 10px;
    width: 60px;
</style>
